package xyz.apiote.bimba.czwek.search

import android.content.Context
import android.net.ConnectivityManager
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import xyz.apiote.bimba.czwek.databinding.ActivityLineGraphBinding
import xyz.apiote.bimba.czwek.repo.OnlineRepository
import xyz.apiote.bimba.czwek.repo.TrafficResponseException
import xyz.apiote.bimba.czwek.search.ui.SectionsPagerAdapter

class LineGraphActivity : AppCompatActivity() {

	private lateinit var binding: ActivityLineGraphBinding
	private lateinit var sectionsPagerAdapter: SectionsPagerAdapter

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)

		binding = ActivityLineGraphBinding.inflate(layoutInflater)
		setContentView(binding.root)

		val lineName = intent.getStringExtra("line")!!
		val feedID = intent.getStringExtra("feedID")!!
		val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
		binding.title.text = lineName
		getGraph(lineName, feedID, cm)
	}

	private fun getGraph(
		lineName: String,
		feedID: String,
		cm: ConnectivityManager,
	) {
		MainScope().launch {
			try {
				val repository = OnlineRepository()
				val line = repository.getLine(cm, feedID, lineName, this@LineGraphActivity)
				line?.let {
					sectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager, it)
					val viewPager: ViewPager = binding.viewPager
					viewPager.adapter = sectionsPagerAdapter
					val tabs: TabLayout = binding.tabs
					// todo [optimisation] hangs before changing progress to graph
					tabs.setupWithViewPager(viewPager)
					binding.lineOverlay.visibility = View.GONE
					binding.viewPager.visibility = View.VISIBLE
				}
			} catch (e: TrafficResponseException) {
				showError(e.error)
				Log.w("Line", "$e")
			}
		}
	}

	private fun showError(e: xyz.apiote.bimba.czwek.api.Error) {
		binding.lineProgress.visibility = View.GONE
		binding.errorImage.visibility = View.VISIBLE
		binding.errorText.visibility = View.VISIBLE
		binding.errorText.text = getString(e.stringResource)
		binding.errorImage.setImageDrawable(AppCompatResources.getDrawable(this, e.imageResource))
	}
}